package com.lagou.consumer;

import com.lagou.request.RpcRequest;
import com.lagou.serialize.JSONSerializer;
import com.lagou.serialize.Serializer;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
//@Component
//@ChannelHandler.Sharable
public class ConsumerHandler extends ChannelInboundHandlerAdapter implements Callable {

    //1.定义成员变量
    private ChannelHandlerContext context; //事件处理器上下文对象 (存储handler信息,写操作)
    private Object result; // 记录服务器返回的数据
    private RpcRequest request; //记录将要返送给服务器的数据

    private Serializer serializer = new JSONSerializer();

    public static List<ChannelHandlerContext> ctxList = new ArrayList<>();

    //2.实现channelActive  客户端和服务器连接时,该方法就自动执行
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //初始化ChannelHandlerContext
        this.context = ctx;
        ctxList.add(ctx);
        System.out.println("ConsumerHandler:"+this);
    }


    //3.实现channelRead 当我们读到服务器数据,该方法自动执行
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //将读到的服务器的数据msg ,设置为成员变量的值
        if(msg instanceof RpcRequest){
            RpcRequest request = (RpcRequest)msg;
            Object returnResult = request.getResult();
            result = returnResult;
        }
        notify();
    }

    //4.将客户端的数写到服务器
    public synchronized Object call() throws Exception {
        //context给服务器写数据
        context.writeAndFlush(request);
//        for (ChannelHandlerContext ctx : ctxList) {
//            ctx.writeAndFlush(request);
//        }
        wait();
        return result;
    }

    //5.设置参数的方法
    public RpcRequest getRequest() {
        return request;
    }

    public void setRequest(RpcRequest request) {
        this.request = request;
    }
}

